<?php
/**
 * Created by PhpStorm.
 * User: 汪汪汪
 * Date: 5/6/14
 * Time: 9:29 AM
 */

namespace App\Controller;

use Think\Controller;


class NewsController extends BaseController
{
    /*资讯分类*/
    public function getCategory()
    {
        $aPage = I('page', 1, 'intval');
        $aCount = I('count', 10, 'intval');
        $aId = I('id', 0, 'intval');

        if ($aId) {
            $category = D('News/NewsCategory')->where(array('status' => 1, 'pid' => $aId))->page($aPage, $aCount)->select();

        } else {
            $category = D('News/NewsCategory')->where(array('status' => 1, 'pid' => 0))->page($aPage, $aCount)->select();

            foreach ($category as &$g) {
                $g['NewsSecond'] = D('News/NewsCategory')->where(array('status' => 1, 'pid' => $g['id']))->select();

                $g['create_time'] = friendlyDate($g['create_time']);
            }
            unset($g);

        }
        $list = array('list' => $category);

        $this->apiSuccess('返回成功', $list);
    }


    //所有的资讯列表
    public function getNewsAll()
    {
        $aPage = I('page', 1, 'intval');
        $aCount = I('count', 10, 'intval');
        $aCate = I('category', 0, 'intval');
        $map['dead_line'] = array('gt', time());
        $map['status'] = 1;

        $order_field = modC('NEWS_ORDER_FIELD', 'create_time', 'News');
        $order_type = modC('NEWS_ORDER_TYPE', 'desc', 'News');
        $order = 'sort desc,' . $order_field . ' ' . $order_type;
        if (empty($aCate)) {
            $News = D('News/News')->where($map)->page($aPage, $aCount)->order($order)->select();

        } else {
            $first = D('News/NewsCategory')->where(array('id' => $aCate, 'status' => 1))->find();

            if ($first['pid'] == 0) {
                $second = D('News/NewsCategory')->where(array('pid' => $first['id'], 'status' => 1))->field('id')->select();

                $ids = array();

                foreach ($second as &$s) {
                    $ids = array_merge($ids, array_column($second, 'id'));
                }
                $map2 = array_merge($ids, array($first['id']));

                $map2['category'] = array('in', $map2);

                $News = D('News/News')->where(array('category' => $map2['category'], $map))->page($aPage, $aCount)->order($order)->select();

            } else {
                $News = D('News/News')->where(array('category' => $first['id'], $map))->page($aPage, $aCount)->order($order)->select();

            }
        }

        foreach ($News as &$c) {
            $c['cover'] = get_cover($c['cover'], 'path');

            if ($c['cover'] === false) {
                $c['cover'] = '';
            }

            $c['dead_line'] = time_format($c['dead_line']);
            $c['create_time'] = friendlyDate($c['create_time']);
            $c['update_time'] = friendlyDate($c['update_time']);
            $c['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $c['uid']);


        }
        unset($c);
        $list = array('list' => $News);

        $this->apiSuccess('返回成功', $list);
    }

    //我的资讯列表
    public function getMyNewsAll()
    {
        $aPage = I('page', 1, 'intval');
        $aCount = I('count', 10, 'intval');
        $this->requireLogin();
        $aStatus = I('status', '', 'intval');
        $aOverdue = I('overdue', '', 'intval');

        if (!empty($aOverdue)) {
            if ($aOverdue === 1) {

                $map2['dead_line'] = array('egt', time());
            }
            if ($aOverdue === 3) {

                $map2['dead_line'] = array('elt', time());
            }
        }
        $map1['status'] = $aStatus;
        if (empty($aStatus)) {
            if (empty($aOverdue)) {
                $News = D('News/News')->where(array('uid' => is_login()))->page($aPage, $aCount)->order('create_time desc')->select();

            } else {
                $News = D('News/News')->where(array('uid' => is_login(), $map2))->page($aPage, $aCount)->order('create_time desc')->select();
            }
        } else {
            if (empty($aOverdue)) {
                $News = D('News/News')->where(array('uid' => is_login(), $map1))->page($aPage, $aCount)->order('create_time desc')->select();
            } else {
                $News = D('News/News')->where(array('uid' => is_login(), $map1, $map2))->page($aPage, $aCount)->order('create_time desc')->select();
            }

        }


        foreach ($News as &$c) {
            $c['cover'] = get_cover($c['cover'], 'path');
            if ($c['dead_line'] <= time()) {
                $c['approval'] = '已过期';
            } else {
                $c['approval'] = '未过期';
            }
            $c['dead_line'] = time_format($c['dead_line']);
            $c['create_time'] = friendlyDate($c['create_time']);
            $c['update_time'] = friendlyDate($c['update_time']);
            $c['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $c['uid']);
        }
        unset($c);
        $list = array('list' => $News);

        $this->apiSuccess('返回成功', $list);
    }

    //推荐的资讯列表
    public function getRecommendNews()
    {
        $News = D('News/News')->where(array('position' => 2, 'status' => 1))->limit(10)->order('view desc')->select();
        foreach ($News as &$c) {
            $c['cover'] = get_cover($c['cover'], 'path');
            $c['dead_line'] = time_format($c['dead_line']);
            $c['create_time'] = friendlyDate($c['create_time']);
            $c['update_time'] = friendlyDate($c['update_time']);
            $c['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $c['uid']);

        }
        unset($c);
        $list = array('list' => $News);

        $this->apiSuccess('返回成功', $list);
    }

    /*热门资讯*/
    public function getHotNewsAll()
    {

        $aCate = I('category', 0, 'intval');
        if (empty($aCate)) {
            $News = D('News/News')->where(array('status' => 1))->limit(10)->order('view desc')->select();

        } else {
            $first = D('News/NewsCategory')->where(array('id' => $aCate, 'status' => 1))->find();

            if ($first['pid'] == 0) {
                $second = D('News/NewsCategory')->where(array('pid' => $first['id'], 'status' => 1))->field('id')->select();

                $ids = array();

                foreach ($second as &$s) {
                    $ids = array_merge($ids, array_column($second, 'id'));
                }
                $map = array_merge($ids, array($first['id']));

                $map['category'] = array('in', $map);

                $News = D('News/News')->where(array($map, 'status' => 1))->limit(10)->order('view desc')->select();

            } else {

                $News = D('News/News')->where(array('category' => $aCate, 'status' => 1))->limit(10)->order('view desc')->select();

            }
        }

        foreach ($News as &$c) {
            $c['cover'] = get_cover($c['cover'], 'path');
            $c['dead_line'] = time_format($c['dead_line']);
            $c['create_time'] = friendlyDate($c['create_time']);
            $c['update_time'] = friendlyDate($c['update_time']);
            $c['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $c['uid']);

        }
        unset($c);
        $list = array('list' => $News);

        $this->apiSuccess('返回成功', $list);
    }

    //资讯详情
    public function getNewsDetail()
    {
        $aId = I('id', 0, 'intval');
        if (!$aId) {
            $this->apiError('请选择资讯');
        }
        $News = D('News/News')->where(array('status' => 1, 'id' => $aId))->find();
        if (!$News) {
            $this->apiError('数据库无此资讯');
        }

        $NewsArticle = D('News/NewsDetail')->where(array('status' => 1, 'news_id' => $aId))->find();
        $News['cover'] = get_cover($News['cover'], 'path');
        $News['create_time'] = friendlyDate($News['create_time']);
        $News['update_time'] = friendlyDate($News['update_time']);
        $News['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $News['uid']);
        $Cate=D('News/NewsCategory')->where(array('id' => $News['category']))->find();
        $News['category_title']=$Cate['title'];
        $arr = array();
        preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $NewsArticle['content'], $arr);

        $News['imgList'] = $arr[1];
        foreach ($arr[0] as $k => $v) {
            $NewsArticle['content'] = str_replace($v, '<-IMG#' . $k . '->', $NewsArticle['content']);

            $News['imgList'][$k] = array('pos' => "<-IMG#{$k}->", 'src' => $arr[1][$k]);
        }
       // $NewsArticle['content']= str_replace('\/','1111',$NewsArticle['content']);
        $News['content'] =$NewsArticle['content'];
        $list = array('list' => $News);

        $this->apiSuccess('返回成功', $list);
    }

    // 返回某个资讯的评论列表
    public function getNewsComments()
    {

        $aPage = I('page', 1, 'intval');
        $aCount = I('count', 10, 'intval');


        $aRowId = I('row_id', 0, 'intval');


        if (!D('News')->where(array('id' => $aRowId))->find()) {
            exit ($this->apiError('活动不存在'));
        }
        $uid = D('News')->where(array('id' => $aRowId))->field('uid')->select();
        $uid = array_column($uid, 'uid');
        $arr = array();
        $NewsComments = D('LocalComment')->where(array('app' => 'News', 'mod' => 'index', 'row_id' => $aRowId, 'status' => 1))->page($aPage, $aCount)->order('create_time desc')->select();
        foreach ($NewsComments as &$v) {
            preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $v['content'], $arr); //匹配所有的图片
            $v['imgList'] = $arr[1];
            $v['content'] = op_t($v['content']);
            $v['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $v['uid']);
            $v['create_time'] = friendlyDate($v['create_time']);

            if (in_array($v['uid'], $uid)) {
                $v['is_landlord'] = '1';
            } else {
                $v['is_landlord'] = '0';
            }

        }
        unset($v);
        $list = array('list' => $NewsComments);
        $this->apiSuccess('返回成功', $list);
    }

    /*发送资讯评论*/
    public function sendNewsComment()
    {
        $this->requireLogin();
        $aRowId = I('row_id', 0, 'intval');
        $aContent = I('content', '', 'op_t');
        $aApp = 'News';
        $aMod = 'index';

        if (!D('News')->where(array('id' => $aRowId))->find()) {
            exit ($this->apiError('专辑不存在'));
        }
        if (!$aContent) {
            exit ($this->apiError('请输入回复内容'));
        }
        $data = array('uid' => is_login(), 'row_id' => $aRowId, 'parse' => 0, 'mod' => $aMod, 'app' => $aApp, 'content' => $aContent, 'status' => '1', 'create_time' => time());

        $data = D('LocalComment')->create($data);

        if (!$data) return false;

        $result = D('LocalComment')->add($data);

        D('News')->where(array('status' => 1, 'id' => $aRowId))->setInc('comment');
        $uid = D('Group/GroupPost')->where(array('id' => $aRowId))->field('uid')->select();
        $uid = array_column($uid, 'uid');
        $reply = D('LocalComment')->where(array('id' => $result))->find();

        preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $reply['content'], $arr); //匹配所有的图片
        $reply['imgList'] = $arr[1];
        $reply['content'] = op_t($reply['content']);
        $reply['create_time'] = friendlyDate($reply['create_time']);
        $reply ['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'));
        if (in_array($reply['uid'], $uid)) {
            $reply['is_landlord'] = '1';
        } else {
            $reply['is_landlord'] = '0';
        }
        $replys=array($reply);
        $list = array('list' => $replys);
        $this->apiSuccess('返回成功', $list);

    }

    public function delNewsComment(){
        $this->requireLogin();
        $aRowId = I('row_id', 0, 'intval');
        $aId = I('id',0, 'intval');


        if (!D('News')->where(array('id' => $aRowId))->find()) {
            exit ($this->apiError('资讯不存在'));
        }
        $Comment=D('LocalComment')->where(array('row_id' => $aRowId, 'status' => '1','id'=>$aId))->find();
        if (!$Comment) {
            exit ($this->apiError('回复不存在'));
        }
        if ($Comment['uid'] == is_login() || is_administrator(is_login())){
            $res = D('LocalComment')->where(array('uid' => is_login(),'id'=>$aId, 'status' => '1'))->setField('status', -1);
            D('News')->where(array('status' => 1, 'id' => $aRowId))->setDec('comment');
            if($res){
                $this->apiSuccess('删除成功');}
            else {
                    $this->apiError('删除操作失败!');
                }
            } else {
                $this->apiError('无权限操作!');
            }
    }


    public function sendNews()
    {
        $this->requireLogin();
        $aId = I('id', 0, 'intval');
        $title = $aId ? "编辑" : "新增";
        if ($aId) {
            $data = $this->getData($aId);
            $this->checkAuth(null, $data['uid'], '你没有编辑该资讯权限！');
            if ($data['status'] == 1) {
                $this->error('该资讯已被审核，不能被编辑！');
            }
        } else {
            $this->checkAuth('News/Index/add', -1, '你没有投稿权限！');
        }
        $aId && $data['id'] = $aId;
        $data['uid'] = I('uid', get_uid(), 'intval');
        $data['title'] = I('title', '', 'op_t');
        $data['content'] = I('content', '', 'op_t');
        $data['category'] = I('category', 0, 'intval');
        $data['description'] = I('description', '', 'op_t');
        $data['cover'] = I('cover', 0, 'intval');
        $data['view'] = I('view', 0, 'intval');
        $data['comment'] = I('comment', 0, 'intval');
        $data['collection'] = I('collection', 0, 'intval');
        $data['sort'] = I('sort', 0, 'intval');
        $data['dead_line'] = I('dead_line', 2147483640, 'intval');
        if ($data['dead_line'] == 0) {
            $data['dead_line'] = 2147483640;
        }
        $data['template'] = I('template', '', 'op_t');
        $data['status'] = I('status', 1, 'intval');
        $data['source'] = I('source', '', 'op_t');
        $data['position'] = 0;
        $position = I('position', '', 'op_t');
        $position = explode(',', $position);
        foreach ($position as $val) {
            $data['position'] += intval($val);
        }

        $this->_checkOk($data);
        $result = $this->editData($data);
        $News = D('News/News')->where(array('status' => 1, 'id' => $result))->find();
        if (!$News) {
            $this->apiError('数据库无此资讯');
        }

        $NewsArticle = D('News/NewsDetail')->where(array('news_id' => $News['id']))->find();

        $News['cover'] = get_cover($News['cover'], 'path');
        $News['create_time'] = friendlyDate($News['create_time']);
        $News['update_time'] = friendlyDate($News['update_time']);
        $News['user'] = query_user(array('uid', 'username', 'nickname', 'avatar128'), $News['uid']);
        $arr = array();
        preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $NewsArticle['content'], $arr);
        $News['imgList'] = $arr[1];

        $News['content'] = op_t($NewsArticle['content']);

        $list = array('list' => $News);
        if ($result) {
            $this->apiSuccess($title . '发表成功！', $list);
        } else {
            $this->apiError($title . '失败！');
        }
    }



    /*********************************************************************************************************************************/

    public function editData($data = array())
    {

        $data['content'] = $this->filterHtmlContent($data['content']);

        if (!mb_strlen($data['description'], 'utf-8')) {
            $data['description'] = msubstr(op_t($data['content']), 0, 200);
        }
        $detail['content'] = $data['content'];
        $detail['template'] = $data['template'];
        $data['reason'] = '';
        if ($data['id']) {
            $data['update_time'] = time();
            $res = D('News/News')->save($data);
            $detail['news_id'] = $data['id'];
        } else {
            $data['create_time'] = $data['update_time'] = time();
            $res = D('News/News')->add($data);
            action_log('add_news', 'News', $res, is_login());
            $detail['news_id'] = $res;
        }
        if ($res) {
            D('News/NewsDetail')->add($detail);
        }
        return $res;
    }

    public function filterHtmlContent($content)
    {
        $content = html($content);
        $content = $this->beforeSave($content);
        $content = filter_base64($content);
        //检测图片src是否为图片并进行过滤
        $content = filter_image($content);
        return $content;
    }

    private function beforeSave($content)
    {
        $content = preg_replace('/\<embed[^>]*?src=\"[^>]*?\.swf[^>]*?\>/', '', $content);
        return $content;
    }

    private function _checkOk($data = array())
    {
        if (!mb_strlen($data['title'], 'utf-8')) {
            $this->apiError('标题不能为空！');
        }
        if (mb_strlen($data['content'], 'utf-8') < 20) {
            $this->apiError('内容不能少于20个字！');
        }
        return true;
    }

    public function getData($id)
    {
        if ($id > 0) {
            $map['id'] = $id;
            $data = $this->where($map)->find();
            if ($data) {
                $data['detail'] = D('News/NewsDetail')->getData($id);
            }
            return $data;
        }
        return null;
    }

}